package com.culturaltourism.admin.service.impl;

import com.culturaltourism.admin.mapper.MySysUserMapper;
import com.culturaltourism.admin.mapper.SysUserMapper;
import com.culturaltourism.admin.pojo.SysUser;
import com.culturaltourism.admin.service.LoginService;
import com.culturaltourism.core.dto.Result;
import com.culturaltourism.core.utils.MD5Util;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @ClassName: LoginServiceImpl
 * @Description: 系统登录实现
 * @Author MaShuai
 * @Date 2019/5/1 19:17
 * @Version V1.0
 */
@Service("LoginService")
public class LoginServiceImpl implements LoginService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private MySysUserMapper mySysUserMapper;


    /**
     * @Description 实现登录
     * @Param [request, sysUser]
     * @Return java.lang.String
     */
    @Override
    public String login(HttpServletRequest request, SysUser sysUser) {

        if (StringUtils.isEmpty(sysUser.getUsername()) || StringUtils.isEmpty(sysUser.getPassword())) {
            return "/login";
        }

        sysUser.setPassword(MD5Util.getMD5Code(sysUser.getPassword()));

        SysUser user = mySysUserMapper.getSysUserByUsernameAndPassword(sysUser);

        if(user != null){
            //把用户数据保存在session域对象中
            //SessionUtil.setUser(user);
            //创建session对象
            HttpSession session = request.getSession();
            //设置session对象10分钟失效
            session.setMaxInactiveInterval(10 * 60);
            //把用户数据保存在session域对象中
            session.setAttribute("user", user);
            return "redirect:/index";
        } else {
            return "/login";
        }
    }

    @Override
    public Result updatePwd(HttpServletRequest request, String oldPwd, String newPwd) {
        // 得到session对象
        HttpSession session = request.getSession(false);
        if(session == null){
            return Result.error("请您先登录！");
        }
        SysUser sysUser = (SysUser) session.getAttribute("user");
        System.out.println(sysUser);
        if (!sysUser.getPassword().equals(MD5Util.getMD5Code(oldPwd))) {
            return Result.error("初始密码错误！");
        }
        sysUser.setPassword(MD5Util.getMD5Code(newPwd));
        int n = sysUserMapper.updateByPrimaryKeySelective(sysUser);
        if(n == 0){
            return Result.error("修改失败！");
        }
        // 注销用户
        request.getSession().invalidate();
        return Result.success("修改成功！");
    }
}
